package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Override
    public void insert(SetmealDto setmealDto) {
        setmealMapper.insert(setmealDto);
    }

    @Override
    public PageInfo<SetmealDto> selectByPage(int page, int pageSize, String name) {
        //开启分页,通过某种方式改变了SQL语句,后面加了limit  起始索引, 查询记录数
        PageHelper.startPage(/*当前第几页*/page,/*每页多少条*/pageSize);
        //查询所有,只返回指定页
        List<SetmealDto> list = setmealMapper.selectAllByName(name);

        for (SetmealDto setmealDto : list) {
            System.err.print(setmealDto.getName() + "========");
            System.err.println(setmealDto.getCategoryName());
        }

        //封装PageInfo
        PageInfo<SetmealDto> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public String delete(String id) {
        Integer status = setmealMapper.selectStatusById(id);
        if (status == 0) {//表示现在是停售状态,才可以删除
            setmealMapper.delete(id);
            setmealDishMapper.deleteBySetmealId(id);
            return "success";
        }
        return "现在不是停售状态,还不能删除该套餐";
    }

    @Override
    public void updateStatus(String id, int is0or1) {//0表示是要切换到停用,1表示要切换到启用
        if (is0or1 == 0) {
            setmealMapper.updateStatus(id, 0);
        } else {
            setmealMapper.updateStatus(id, 1);
        }
    }

    @Override
    public SetmealDto selectAllById(String id) {
        SetmealDto setmealDto = setmealMapper.selectAllById(id);//这个setmealDtp中缺少List<SetmealDish> setmealDishes,需要根据setmealId查询setmeal_dish表

        List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(setmealDto.getId());

        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }


    @Override
    public void updateById(SetmealDto setmealDto) {//修改 setmeal 表中 name,price,category_id,image,description,update_time,update_user属性
        setmealMapper.updateById(setmealDto);
    }

    @Override
    public List<Setmeal> selectByCategoryId(String categoryId) {
        return setmealMapper.selectByCategoryId(categoryId);
    }
}
